package whu.iss.web.support;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet("*.html")
public class BaseServlet extends HttpServlet 
{
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String path=null;
		try
		{
			String uri=request.getRequestURI();
			int index=uri.lastIndexOf("/");
			String uriName=uri.substring(index+1);
			String baseName=uriName.replaceAll(".html", "").toUpperCase();

				String packageName=uriName.substring(0, 2);

				String servletClassName="com.neusoft.web."+packageName+".impl."+baseName+"Servlet";
				
				BaseController controller=(BaseController) Class.forName(servletClassName).newInstance();

				controller.setDto(this.createDto(request));

				controller.initOptions();
				
				path=controller.execute();
				
				this.setRequestAttribute(controller.getAttributes(), request);
				controller.clearAttributes();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		} 
		request.getRequestDispatcher("/"+path+".jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		this.doGet(request, response);
	}

	private final void setRequestAttribute(Map<String,Object> atts,HttpServletRequest request)
	{
		Set<Entry<String,Object>> entrySet=atts.entrySet();
		for(Entry<String,Object> entry:entrySet)
		{
			request.setAttribute(entry.getKey(), entry.getValue());
		}
	}
	
	
    private final Map<String,Object> createDto(HttpServletRequest request)
    {
		Map<String,String[]> tem=request.getParameterMap();
		Set<Entry<String,String[]>> entrySet=tem.entrySet();
		String value[]=null;
		Map<String,Object> dto=new HashMap<>();
		for(Entry<String,String[]>  entry:entrySet)
		{
			value=entry.getValue();
			if(value.length==1)
			{
				dto.put(entry.getKey(), value[0]);
			}
			else
			{
				dto.put(entry.getKey(), value);
			}	
		 }
		 return dto;
    }

}
